package com.company;

import java.sql.*;

public class MysqlConnection {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        String url = "jdbc:mysql://localhost:3306/teacher_mgmt";
        String user = "root";
        String password = "123456";
        String sql = "select teach_id, teach_name, password, major from teachers where teach_name = ?";

        try (
                Connection conn = DriverManager.getConnection(url, user, password);
                PreparedStatement pstmt = conn.prepareStatement(sql)
        ) {
            // 设置查询参数
            pstmt.setString(1, "张三");
            // 使用嵌套的 try-with-resources 来管理 ResultSet
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    Teacher teacher = new Teacher(
                            rs.getString("teach_id"),
                            rs.getString("teach_name"),
                            rs.getString("password"),
                            rs.getString("major")
                    );
                    System.out.println(teacher);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
